package com.xaomn.controller;

import com.xaomn.api.yjs.LoginControllerApi;
import com.xaomn.module.SysUserVo;
import com.xaomn.response.BaseResponse;
import com.xaomn.response.Status;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author xaoMn
 * @title: LoginController
 * @projectName yjs
 * @description: TODO
 * @date 日期：2022/1/25 时间：23:08
 */
@RestController
@RequestMapping("/common")
public class LoginController implements LoginControllerApi {
    private static final Logger log = LogManager.getFormatterLogger();


    @GetMapping("/login")
    public BaseResponse login(SysUserVo sysUser) {

        Subject currentUser = SecurityUtils.getSubject();
        if (!currentUser.isAuthenticated()) {
            // 如果没有完成认证
            UsernamePasswordToken token = new UsernamePasswordToken(sysUser.getUserName(), sysUser.getPassword());
            try {
                currentUser.login(token);
                currentUser.getSession().setAttribute("currentUser", currentUser.getPrincipal());
                return new BaseResponse<SysUserVo>(Status.SUCCESS);
            } catch (UnknownAccountException uae) {
                log.info("%s用户不存在！", token.getPrincipal());
                return new BaseResponse<SysUserVo>(Status.LOGIN_ERROR);
            } catch (IncorrectCredentialsException ice) {
                log.info("%s密码是错误！", token.getPrincipal());
                return new BaseResponse<SysUserVo>(Status.LOGIN_ERROR);
            } catch (LockedAccountException lae) {
                log.info("%s账户被锁定！", token.getPrincipal());
                return new BaseResponse<SysUserVo>(Status.LOGIN_USER_STATUS_ERROR);
            } catch (AuthenticationException lae) {
                return new BaseResponse<SysUserVo>(Status.LOGIN_EXPIRE);
            }
        }
        return new BaseResponse<SysUserVo>(Status.SUCCESS);
    }

    @RequestMapping("getCurrentUser")
    public Object getCurrentUser() {
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        return session.getAttribute("currentUser");
    }
}
